<?php
namespace tp5_lib\aliyun\utility;

require_once '../extend/aliyun_sms/vendor/autoload.php';

use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use tp5_lib\notice\Notice;

/**
 * 调用阿里云短信接口
 * 改写自PHP Demo
 * @see https://help.aliyun.com/document_detail/55359.html?spm=a2c4g.11186623.2.16.3ee73a76R8psaL
 */
class Sms extends Notice
{
    static protected $_instance=null;
    public $client=null;
    /**
     * @return self
     */
    static public function instance()
    {
        if(static::$_instance === null){
            Config::load();
            $product = "Dysmsapi";
            $domain = "dysmsapi.aliyuncs.com";
            $accessKeyId = "LTAIwGjEl0mkfvfI";
            $accessKeySecret = "x7CjvTh2fGZTICwARzRPtjtzsw44q3";
            $region = "cn-hangzhou";
            $endPointName = "cn-hangzhou";
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
            $instance = new static();
            $instance->client=new DefaultAcsClient($profile);
            static::$_instance = $instance;
        }
        return static::$_instance;
    }
    /**
     * @return bool
Message:"OK"
RequestId:"68F2B8BA-733D-42E9-9E8D-8465DF6ED2DB"
BizId:"163625159273551711^0"
Code:"OK"
     */
    public function send($mobile,$template,$params,$id="")
    {
        $request = new SendSmsRequest();
        //$request->setProtocol("https");
        $request->setPhoneNumbers($mobile);
        $request->setSignName("空气巴巴");
        $request->setTemplateCode($template);
        $request->setTemplateParam(json_encode($params, JSON_UNESCAPED_UNICODE));
        $request->setOutId($id);
        $request->setSmsUpExtendCode("1234567");
        try {
            $response=$this->client->getAcsResponse($request);
            if($response->Code !== "OK"){
                $this->error = "Code:".$response->Code .";Message:".$response->Message;
                return false;
            }
            return true;
        } catch (\Exception $th) {
            $this->error="发送失败:".$th->Message;
            return false;
        }
    }
    public function sendVerifyCode($mobile,$code,$id="")
    {
        return $this->send($mobile,"SMS_152857848",["code"=>$code],$id);
    }
}
